<?php
namespace app\controller;

use think\facade\Db;
use think\facade\Request;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Logo\Logo;
use think\response\File;

class QrController
{
    public function export()
    {
        try {
           
            // 添加URL
            $params = Request::param();
            $qr_sn = $params['qr_sn'];
            
            // 先查询 qrcode_p 表
            $item = Db::name('qrcode_p')->where('qr_sn', $qr_sn)->find();
            if(!$item){
                $item = Db::name('qrcode')->where('qr_sn', $qr_sn)->find();
            }

            if(!$item){
                throw new \Exception('二维码不存在');
            }

            $domain = Request::domain();
            $item['url'] = $domain.'/qrcode/?id='.$item['qr_sn'];
            // 生成单个二维码
           $qrFilePath = $this->generateSingleQr($item);
            
            return $this->outputQrFile($qrFilePath);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 生成单个二维码
     */
    private function generateSingleQr(array $item): string
    {
        $tempDir = $this->getTempDir();
        
        // 修复：将简写的 throw 改为 if 判断
        if (!extension_loaded('gd')) {
            throw new \Exception('请启用PHP的GD扩展');
        }

        // 生成基础二维码
        $qrCode = QrCode::create($item['url'])
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->setSize(300);
        
        if($item['pid']==0){
            // 生成完全居中的数字图片
            $numberLogoPath = $this->generateFullCenteredNumberImage($item['id'], $tempDir);
            
            // 嵌入数字Logo
            $logo = Logo::create($numberLogoPath)
                ->setResizeToWidth(70);
            
            $filename = "boxCode_{$item['id']}.png";
            $filePath = $tempDir . $filename;
            file_put_contents($filePath, (new PngWriter())->write($qrCode, $logo)->getString());
            
            @unlink($numberLogoPath);
        }else{
            $filename = "boxCode_{$item['pid']}_goodsCode.png";
            $filePath = $tempDir . $filename;
            file_put_contents($filePath, (new PngWriter())->write($qrCode)->getString());
        }
        
        return $filePath;
    }

    /**
     * 生成水平+垂直完全居中的数字图片
     */
    private function generateFullCenteredNumberImage(int $number, string $tempDir): string
    {
        $imageSize = 100;
        $image = imagecreatetruecolor($imageSize, $imageSize);

        // 白色背景
        $white = imagecolorallocate($image, 255, 255, 255);
        imagefill($image, 0, 0, $white);

        // 字体配置
        $fontPath = $this->getFontPath();
        // 修复：将简写的 throw 改为 if 判断
        if (!file_exists($fontPath)) {
            throw new \Exception("字体文件不存在：{$fontPath}");
        }

        // 动态调整字体大小
        $numberStr = (string)$number;
        switch (strlen($numberStr)) {
            case 1:
                $fontSize = 45;
                break;
            case 2:
                $fontSize = 38;
                break;
            case 3:
                $fontSize = 30;
                break;
            default:
                $fontSize = 25;
        }

        // 计算文字边界
        $bbox = imagettfbbox($fontSize, 0, $fontPath, $numberStr);
        $textWidth = $bbox[2] - $bbox[0];
        $textHeight = $bbox[1] - $bbox[7];

        // 计算居中坐标
        $x = ($imageSize - $textWidth) / 2 - $bbox[0];
        $y = ($imageSize / 2) + ($textHeight / 2) - $bbox[1];

        // 绘制数字
        $black = imagecolorallocate($image, 0, 0, 0);
        imagettftext($image, $fontSize, 0, (int)$x, (int)$y, $black, $fontPath, $numberStr);

        // 保存图片
        $imagePath = $tempDir . "num_{$number}.png";
        imagepng($image, $imagePath);
        imagedestroy($image);

        return $imagePath;
    }

    // 字体路径
    private function getFontPath(): string
    {
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            return 'C:/Windows/Fonts/simhei.ttf';
        }
        // 宝塔路径 项目根目录下的fonts目录
        // return __DIR__ . '/../public/fonts/simhei.ttf';
        // // return '/www/wwwroot/yl.lizuzhe.com/public/fonts/simhei.ttf';
        $path = dirname(__FILE__);
        // 把 /app/controller 替换为 /public/fonts
        $path = str_replace('/app/controller', '/public/fonts/simhei.ttf', $path);
        return $path;
    }

    /**
     * 输出二维码文件
     */
    private function outputQrFile(string $qrFilePath): File
    {
        ob_end_clean();
        return (new File($qrFilePath, 200))->header([
            'Content-Type' => 'image/png',
            'Cache-Control' => 'max-age=0',
            'Content-Disposition' => 'attachment; filename="' . basename($qrFilePath) . '"'
        ]);
    }

    // 获取临时目录
    private function getTempDir(): string
    {
        $tempDir = sys_get_temp_dir() . '/qr_batch_temp/';
        if (!is_dir($tempDir)) {
            mkdir($tempDir, 0777, true);
        }
        return $tempDir;
    }

    // 过滤文件名
    private function filterFilename(string $filename): string
    {
        return preg_replace('/[^\w\-\.]+/', '_', $filename);
    }
}